package models

import (
	"awesome-devops/applications/tools"
	"awesome-devops/boot"
	"awesome-devops/helper"
	"fmt"
	"gitee.com/jjawesomejj/awesome-util/config"
	"gitee.com/jjawesomejj/awesome-util/helper/commonhelper"
	"gitee.com/jjawesomejj/awesome-util/helper/timeHelper"
	"gorm.io/gorm"
	"strconv"
	"time"
)

const ENABLE_WEBHOOK = 1

type Project struct {
	BaseModel
	ID                uint      `json:"id"`
	ProjectName       string    `json:"project_name"`
	Description       string    `json:"description"`
	Branch            string    `json:"branch"`
	GitUrl            string    `json:"git_url"`
	Labels            string    `json:"labels"`
	WebhookRequestKey string    `json:"webhook_request_key"`
	EnableWebHook     int       `json:"enable_web_hook"`
	CreateTime        time.Time `json:"create_time"`
	UpdateTime        time.Time `json:"update_time"`
	DeleteTime        int       `json:"delete_time"`
}

func (baseModel *Project) BeforeCreate(tx *gorm.DB) (err error) {
	if baseModel.EnableWebHook == ENABLE_WEBHOOK {
		baseModel.WebhookRequestKey = commonhelper.Md5(fmt.Sprintf("%f", timeHelper.NowFloat()) + commonhelper.Rand(10))
	}
	baseModel.CreateTime = time.Now()
	baseModel.UpdateTime = time.Now()
	return tx.Error
}

func (baseModel *Project) GetRunnerLabels() []int {
	labelIds := baseModel.Labels
	var data []int
	err := commonhelper.JsonDecodeWithType(labelIds, &data)
	if err != nil {
		return make([]int, 0)
	} else {
		return data
	}

}

func (baseModel *Project) BeforeUpdate(tx *gorm.DB) (err error) {
	if baseModel.EnableWebHook == ENABLE_WEBHOOK {
		baseModel.WebhookRequestKey = commonhelper.Md5(fmt.Sprintf("%f", timeHelper.NowFloat()) + commonhelper.Rand(10))
	}
	baseModel.UpdateTime = time.Now()
	return tx.Error
}
func (baseModel *Project) TableName() string {
	return "ops_project"
}

func GetGitCommand(project Project) (*tools.GitCommand, error) {
	gitCommand := tools.GitCommand{
		WorkDir: config.GetConfigByKey("GitProjectPath", func() interface{} {
			return "../../projects/"
		}).(string),
		ProjectDir: strconv.Itoa(int(project.ID)),
		GitSshUrl:  project.GitUrl,
	}
	gitCommand.WorkDir += "git/"
	_, err := gitCommand.Init()
	if err != nil {
		return nil, err
	}
	return &gitCommand, nil
}

func GetProjectBy(project Project) (*tools.GitCommand, error) {
	gitCommand := tools.GitCommand{
		WorkDir: config.GetConfigByKey("GitProjectPath", func() interface{} {
			return "../../projects/"
		}).(string),
		ProjectDir: strconv.Itoa(int(project.ID)),
		GitSshUrl:  project.GitUrl,
	}
	gitCommand.WorkDir += "git/"
	_, err := gitCommand.Init()
	if err != nil {
		return nil, err
	}
	return &gitCommand, nil
}

func GetDeployGitCommand(project Project) (*tools.GitCommand, error) {
	projectGitCommand, err := GetGitCommand(project)
	if err != nil {
		return nil, err
	}
	gitCommand := tools.GitCommand{
		WorkDir: config.GetConfigByKey("GitProjectPath", func() interface{} {
			return "../../projects/"
		}).(string),
		ProjectDir: strconv.Itoa(int(project.ID)),
		GitSshUrl:  project.GitUrl,
	}
	gitCommand.WorkDir += "deploy/"
	gitCommand.ResolvePath()
	exist, err := helper.PathExists(gitCommand.GitProjectPath + "/" + ".git")
	if err != nil {
		return nil, err
	}
	if exist == false {
		err = helper.Dir(projectGitCommand.GitProjectPath, gitCommand.GitProjectPath)
		if err != nil {
			return nil, err
		}
	}
	return &gitCommand, nil
}

func GetProjectByAccessToken(accessToken string) (*Project, error) {
	model := Project{}
	res := boot.GetDbConnection().
		Where("webhook_request_key", accessToken).
		Where("enable_web_hook", ENABLE_WEBHOOK).Where("delete_time=0").First(&model)
	return &model, res.Error
}
